<?php
namespace app\api\service;

use app\api\modal\Product as ProductModel;
use app\api\modal\Order as OrderModel;
use app\api\model\UserAddress as UserAddressModel;
use app\lib\exception\UserException;

class Order{
    //订单的商品列表，也就是客户端传递过来的products参数
    protected $oProducts;

    //真实的商品信息（包括库存量）
    protected $products;

    protected $uid;

    public function place($uid, $oProducts){
        //oProducts和products做对比
        //products从数据库查询出来
        $this->oProducts = $oProducts; 
        $this->products = '';
        $this->uid = $uid;
        $status = $this->getOrderStatus();
        if(!$status['pass']){
            $status['order_id'] = -1;
            return $status;
        }

        //开始创建订单
        $orderSnap = $this->snapOrder();


    }

    private function createOrder($snap){
        $orderNo = $this->makeOrderNo();
        $order = new OrderModel();
        $order->user_id = $this->uid;
        $order->order_no = $orderNo;
        $order->total_price = $snap['orderPrice'];
        $order->total_count = $snap['totalCount'];
        $order->snap_img = $snap['snapImg'];
        $order->snap_name = $snap['snapName'];
        $order->snap_address = $snap['snapAddress'];
        $order->snap_items = json_encode($snap['pStatus']);

        $order->save();

        $orderID = $order->id;
        foreach($this->oProducts as &$p){
            $p['order_id'] = $orderID;
        }

    }

    //生成订单号
    public static function makeOrderNo(){
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y') - 2017)] . strtotime(dechex(date('m'))) 
                . data('d') . substr(time(), -5) . substr(microtime(), 2, 5)
                . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

    //生成订单快照
    private function snapOrder($status){
        $snap = [
            'orderPrice' => 0,
            'totalCount' => 0,
            'pStatus' => [],
            'snapAddress' => '',
            'snapName' => '',
            'snapImg' => ''
        ];

        $snap['orderPrice'] = $status['orderPrice'];
        $snap['totalCount'] = $status['totalCount'];
        $snap['pStatus'] = $status['pStatusArray'];
        $snap['snapAddress'] = json_encode($this->getUserAddress());
        $snap['snapName'] = $this->product[0]['name'];
        $snap['snapImg'] = $this->product[0]['main_img_url'];
    }

    private function getUserAddress(){
        $userAddress  = UserAddressModel::where('user_id', '=', $this->uid)
                    ->find();
        if(!$userAddress){
            throw new UserException([
                'msg' => '用户收货地址不存在，下单失败',
                'errorCode' => 60001
            ]);
        }
        return $userAddress->toArray();
    }

    private function getOrderStatus(){
        $status = [
            'pass' => true,
            'orderPrice' => 0,
            'totalCount' => 0,
            'pStatusArray' => []
        ];

        foreach($this->oProducts as $oProduct){
            $pStatus = $this->getProductStatus(
                $oProduct['product_id'], $oProduct['count'], $this->products
            );
            if(!$pStatus['haveStock']){
                $status['pass'] = false;
            }
            $status['orderPrice'] += $pStatus['totalPrice'];
            $status['totalCount'] += $pStatus['totalCount'];
            array_push($status['pStatusArray'], $pStatus);
        }
    }

    private function getProductStatus($oPIS, $oCount, $products){
        $pIndex = -1;
        $pStatus = [
            'id' => null,
            'havaStock' => false,
            'count' => 0,
            'name' => '',
            'totalPrice' => 0
        ];
        for($i=0,$len=count($products); $i<$len; $i++){
            if($oPID == $products[$i]['id']){
                $pIndex = $i;
            }
        }
        if($pIndex == -1){
            //客户端传递的product_id有可能不存在
            throw new OrderException([
                'msg' => 'id为'.$oPID.'的商品不存在，创建订单失败'
            ]);
        }else{
            $product = $products[$pIndex];
            $pStatus['id'] = $product['id'];
            $pStatus['count'] = $oCount;
            $pStatus['totalPrice'] = $product['price'] * $oCount;
            if($product['stock'] - $oCount >=0){
                $pStatus['haveStock'] = true;
            }
        }
        return $pStatus;
    }

    //根据订单信息查找真实的商品信息
    private function getProductsByOrder($oProducts){
        $oPIDS = [];
        foreach($oProducts as $item){
            array_push($oPIDS, $item['product_id']);
        }
        $products = ProductModel::all($oPIDS)
                ->visible(['id', 'price', 'stock', 'name', 'main_img_url'])
                ->toArray(); //将其转为数组
        return $products;
    }
}

?>